package com.wqj.kyee.gps.bluetooth.client

import android.bluetooth.BluetoothSocket
import android.bluetooth.BluetoothDevice
import android.os.Handler
import android.os.Message
import android.util.Log
import com.wqj.kyee.gps.bluetooth.BluetoothDeviceDean
import com.wqj.kyee.gps.bluetooth.BtDevicesActivity
import java.io.IOException
import java.util.*
import java.util.concurrent.locks.ReentrantLock


/**
 * Created by kyee on 17-12-8.
 */
public class BtClientThread(val mmDevice: BluetoothDeviceDean, handler: Handler) : Thread() {
    private val TAG: String = "BTClientThread"
    private val mmSocket: BluetoothSocket?
    private val lock = ReentrantLock()

    public var btd :BluetoothDevice? =null
//    private var mHandler: Handler
//    private var isConnected = false;

    init {
        // Use a temporary object that is later assigned to mmSocket,
        // because mmSocket is final
        var tmp: BluetoothSocket? = null
        val uuid = UUID.fromString(BtDevicesActivity.BT_UUID)
        Log.d(TAG, "Start client connect thread")
        mHandler = handler
        btd = mmDevice.getBluetoothDevice()
        // Get a BluetoothSocket to connect with the given BluetoothDevice
        try {
            // MY_UUID is the app's UUID string, also used by the server code
            tmp = mmDevice.getBluetoothDevice().createRfcommSocketToServiceRecord(uuid)
        } catch (e: IOException) {
        }
        mmSocket = tmp
        btClientThread = this;
    }

    override fun run() {
        // Cancel discovery because it will slow down the connection
        lock.lock()
        BtDevicesActivity.bluetoothAdapter.cancelDiscovery()
        Log.d(TAG, "Start connect to bt-gps: " + mmSocket)
        try {
            // Connect the device through the socket. This will block
            // until it succeeds or throws an exception
            mmSocket!!.connect()
            val msg = Message.obtain()
            msg.what = BtDevicesActivity.BT_CLIENT_CONNECT_SUCCESS
            msg.data.putParcelable("btdevice",mmDevice.getBluetoothDevice());
            mHandler?.sendMessage(msg)
            Log.d(TAG, "connect success")
            BtDevicesActivity.connectedSock = mmSocket
        } catch (connectException: IOException) {
            // Unable to connect; close the socket and get out
            Log.d(TAG, "failed: " + connectException.message)
            val msg = Message.obtain()
            msg.what = BtDevicesActivity.BT_CLIENT_CONNECT_FAIL
            msg.data.putParcelable("btdevice",mmDevice.getBluetoothDevice());
            mHandler?.sendMessage(msg)
            try {
                mmSocket!!.close()
            } catch (closeException: IOException) {
            }
            lock.lock()
            return
        }
        lock.unlock()
        // Do work to manage the connection (in a separate thread)
        // manageConnectedSocket(mmSocket)
    }

    /** Will cancel an in-progress connection, and close the socket  */
    fun cancel() {
        try {
            mmSocket!!.close()
            val msg = Message.obtain()
            msg.what = BtDevicesActivity.BT_SERVER_DISCONNECT_SUCCESS
            btClientThread = null;
            msg.data.putParcelable("btdevice",mmDevice.getBluetoothDevice());
            mHandler?.sendMessage(msg)
        } catch (e: IOException) {
        }
    }

    fun isContected() :Boolean{
        return mmSocket!!.isConnected()
    }

    companion object{
        var mHandler: Handler?= null;
        var btClientThread: BtClientThread?= null;
    }
}